const express = require("express");
const fs = require('fs')
const path = require('path')
const router = express.Router();
const multer = require('multer');
var upload = multer({ dest: 'uploads/' });

router.post('/image', upload.single('img'), function (req, res) {
  //读取文件路径(uploads/文件夹下面的新建的图片地址)
  fs.readFile(req.file.path, (err, data) => {
    //如果读取失败
    if (err) {
      return res.send({
        code: 30001,
        message: '上传图片失败'
      })
    }
    //如果读取成功
    //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性
    let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
    //拓展名
    let extname = req.file.mimetype.split('/')[1]
    //拼接成图片名
    let keepname = time + '.' + extname
    //三个参数
    //1.图片的绝对路径
    //2.写入的内容
    //3.回调函数
    console.log(path.resolve(__dirname, '../public/img/' + keepname))
    fs.writeFile(path.resolve(__dirname, '../public/images/' + keepname), data, (err) => {
      if (err) {
        return res.send({
          code: 30002,
          message: '图片写入失败'
        })
      }
      res.send({code: 200, msg: '上传ok', data: 'http://127.0.0.1:3000/images/' + keepname})
    });
  });
})


module.exports = router;